package com.kime.shiro.base;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: JiangYi
 * @Date: 2022-03-13 16:41:57
 * @Description: shiro 学习教程
 */
public class TestAuthenticator {
    public static void main(String[] args) {

        // 1. 创建安全管理器对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // 2. 给安全管理器设置 realms
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));

        // 3. SecurityUtils 给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        // 4. 关键对象 subject 主体
        Subject subject = SecurityUtils.getSubject();

        // 5. 创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");

        try {
            // 6. 用户认证
            // subject.isAuthenticated() true --> 认证成功，false --> 认证失败
            System.out.println("认证状态: " + subject.isAuthenticated());
            subject.login(token);
            System.out.println("认证状态: " + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("认证失败: 用户名不存在～ ");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("认证失败: 密码错误～");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("认证失败: 其它异常～");
        }

        // 认证用户进行授权
        if (subject.isAuthenticated()) {
            // 基于角色权限控制
            System.out.println(subject.hasRole("admin"));
        }
    }
}
